package com.teach.util.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.teach.R;
import com.teach.util.JsonUtil;

/** <pre>
 * json处理工具类
 * ClassName : com.teach.commons.Json
 * Author : J.L.Zhou
 * Date : 2020-03-04 12:51
 * Version : V1.0
 * Copyright 2020 jlzhou.top Inc. All rights reserved. 
 * Warning: this content is only for internal circulation of the company. It is forbidden to divulge it or use it for other commercial purposes</pre>
 */
@Component
@ConditionalOnBean(ObjectMapper.class)
@AutoConfigureAfter(ObjectMapper.class)
public class JsonUtilImpl implements JsonUtil {
	 
	public ObjectMapper mapper;
	
	public JsonUtilImpl(ObjectMapper mapper) {
		super();
		this.mapper = mapper;
	}

	public String toString(Object obj) {
		try {
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new RuntimeException("序列化json字符串错误", e);
		}
	}
	

	@Override
	public String toPrettyString(Object obj) {
		try {
			return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new RuntimeException("序列化json字符串错误", e);
		}
	}
	
	public <E> E toBean(String str,Class<E> cls) {
		try {
			return mapper.readValue(str, cls);
		} catch (Exception e) {
			throw new RuntimeException("反序列化成java对象错误", e);
		}
	}
	
	public <E> List<E> toList(String str,Class<E> cls) {
		try {
			return mapper.readValue(str, mapper.getTypeFactory().constructParametricType(ArrayList.class, cls));
		} catch (Exception e) {
			throw new RuntimeException("反序列化成List对象错误", e);
		}
	}
	
	public <K,V> Map<K,V> toMap(String str,Class<K> keyClass,Class<V> valueClass) {
		try {
			return mapper.readValue(str, mapper.getTypeFactory().constructParametricType(HashMap.class, keyClass,valueClass));
		} catch (Exception e) {
			throw new RuntimeException("反序列化成Map对象错误", e);
		}
	}
	
	public <T> R<T> toR(String str,Class<T> cls){
		try {
			return mapper.readValue(str, mapper.getTypeFactory().constructParametricType(R.class, cls));
		} catch (Exception e) {
			throw new RuntimeException("反序列化成ReturnData对象错误", e);
		}
	}

}
